package com.yanjr.modules.ad.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yanjr.common.persistence.Page;
import com.yanjr.common.utils.IdGen;
import com.yanjr.common.utils.StringUtils;
import com.yanjr.modules.ad.dao.AdvertisementDao;
import com.yanjr.modules.ad.entity.Advertisement;
import com.yanjr.modules.ad.service.AdvertisementService;

@Service("advertisementService")
@Transactional(readOnly = true)
public class AdvertisementServiceImpl implements AdvertisementService {

	@Autowired
	private AdvertisementDao advertisementDao;

	@Override
	public Advertisement get(String id) {
		return advertisementDao.get(id);
	}

	@Override
	@Transactional(readOnly = false)
	public void save(Advertisement advertisement) {
		if(StringUtils.isEmpty(advertisement.getId())) {
			advertisement.setId(IdGen.uuid());
			advertisementDao.save(advertisement);
		} else {
			advertisementDao.update(advertisement);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(String id) {
		advertisementDao.delete(id);
	}

	@Override
	public Page<Advertisement> find(Page<Advertisement> page, Advertisement advertisement) {
		StringBuffer sql = new StringBuffer("select * from advertisement where 1=1 ");
		
		if(StringUtils.isNotEmpty(advertisement.getSpaceId())) {
			sql.append("and space_id='" + advertisement.getSpaceId() + "' ");
		}
		if(StringUtils.isNotEmpty(advertisement.getName())) {
			sql.append("and name like '%" + advertisement.getName() + "%' ");
		}
		
		return advertisementDao.findPage(page, sql.toString());
	}

	@Override
	public Page<Advertisement> find(Page<Advertisement> page, String id,
			Advertisement advertisement) {
//		String sql = "";
		
		
		return null;
	}

	@Override
	@Transactional(readOnly = false)
	public void enableById(String id) {
		advertisementDao.enableById(id);
	}

	@Override
	@Transactional(readOnly = false)
	public void disenableById(String id) {
		advertisementDao.disenableById(id);
	}

	@Override
	public List<Advertisement> findAllEnable(String spaceId) {
		String sql = "select * from advertisement where space_id=? and is_enable=1 and start_time<=now() and end_time>=now()";
		return advertisementDao.findList(sql, new Object[]{spaceId});
	}
	


}
